package cn.mrcode.wxsdk.core.zkhelper.curator;

import cn.mrcode.wxsdk.core.context.ConfigContext;
import cn.mrcode.wxsdk.core.dialogue.common.PublicAccount;
import cn.mrcode.wxsdk.core.dialogue.common.accessToken.AccessTokenApi;
import cn.mrcode.wxsdk.core.dialogue.protocol.base.AccessTokenInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.curator.framework.CuratorFramework;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *  手动重置 zk上的数据
 * @author zhuqiang
 * @version V1.0
 * @date 2016/6/28
 */
public class CoreResetDataHelper {
    public static Map<String, AccessTokenInfo> resetToken(CuratorFramework client, ConfigContext configContext) throws Exception {
        Map<String, AccessTokenInfo> result = new HashMap<>();
        List<AccessTokenInfo> data = new ArrayList<AccessTokenInfo>();
        for (Map.Entry<String, PublicAccount> entry : configContext.getDirstributedConfig().getPublicAccountMap().entrySet()) {
            String key = entry.getKey();
            PublicAccount publicAccount = entry.getValue();
            AccessTokenInfo accessTokenInfo = AccessTokenApi.getAccessTokenInfo(publicAccount.getAppID(), publicAccount.getAppSecret());
            accessTokenInfo.setLastUpdateBy(configContext.getId());
            data.add(accessTokenInfo);
            result.put(accessTokenInfo.getAppID(), accessTokenInfo);
        }
        client.setData().forPath(ConfigContext.masterPath_basetoken, JSONObject.toJSONString(data).getBytes());
        return result;
    }
}
